package com.ef.web.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.hibernate.Criteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;

import com.ef.constant.ConfirmMessage;
import com.ef.constant.StatusType;
import com.ef.domain.Department;
import com.ef.domain.Role;
import com.ef.domain.School;
import com.ef.domain.Team;
import com.ef.domain.User;
import com.ef.service.DepartmentService;
import com.ef.service.RoleService;
import com.ef.service.SchoolService;
import com.ef.service.TeamService;
import com.ef.service.UserService;
import com.ef.util.CustomExample;

public class UserAction extends BaseAction<User> {

	private static final long serialVersionUID = 1L;

	protected final org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory
			.getLog(UserAction.class);
	private UserService userService;

	private RoleService roleService;
	private SchoolService schoolService;
	private TeamService teamService;
	private DepartmentService departmentService;

	private Map<String, String> roleList;
	private Map<String, String> schoolList;
	private Map<String, String> teamList;
	private Map<String, String> departmentList;

	private String selName;

	private String selRole;

	private String selDep;

	private String selSchool;

	public String getSelName() {
		return selName;
	}

	public void setSelName(String selName) {
		this.selName = selName;
	}

	public String getSelRole() {
		return selRole;
	}

	public void setSelRole(String selRole) {
		this.selRole = selRole;
	}

	public String getSelDep() {
		return selDep;
	}

	public void setSelDep(String selDep) {
		this.selDep = selDep;
	}

	public String getSelSchool() {
		return selSchool;
	}

	public void setSelSchool(String selSchool) {
		this.selSchool = selSchool;
	}

	@SuppressWarnings("serial")
	public String list() {
		fetchListData();
		this.listResult = userService.findByExample(new CustomExample<User>(
				this.getModel()) {
			public void appendCondition(Criteria criteria) {
				if (selName != null && selName.trim().length() > 0) {
					criteria.add(Restrictions.like("name", selName.trim(),
							MatchMode.ANYWHERE));
				}
				if (selSchool != null && selSchool.trim().length() > 0) {
					criteria.createCriteria("school").add(
							Restrictions
									.eq("id",Long.valueOf(selSchool.trim())));
				}
				if (selRole != null && selRole.trim().length() > 0) {
					criteria.createCriteria("role").add(
							Restrictions
									.eq("id",Long.valueOf(selRole.trim())));
				}
				if (selDep != null && selDep.trim().length() > 0) {
					criteria.createCriteria("department").add(
							Restrictions
									.eq("id",Long.valueOf(selDep.trim())));
				}
			}
		}, this.getStartIndex(), this.getPageSize());
		return LIST;
	}

	public String edit() {
		fetchListData();
		return EDIT;
	}

	private void fetchListData() {
		Map<String, String> roleMap = new LinkedHashMap<String, String>();
		List<Role> roles = roleService.findAll();
		for (Role r : roles) {
			if (r.getStatus() == StatusType.VALID)
				roleMap.put(r.getId().toString(), r.getName());
		}
		roleList = roleMap;

		Map<String, String> schoolMap = new LinkedHashMap<String, String>();
		List<School> schools = schoolService.findAll();
		for (School s : schools) {
			if (s.getStatus() == StatusType.VALID)
				schoolMap.put(s.getId().toString(), s.getName());
		}
		schoolList = schoolMap;

		Map<String, String> teamMap = new LinkedHashMap<String, String>();
		List<Team> teams = teamService.findAll();
		for (Team t : teams) {
			if (t.getStatus() == StatusType.VALID)
				teamMap.put(t.getId().toString(), t.getName());
		}
		teamList = teamMap;
		Map<String, String> depMap = new LinkedHashMap<String, String>();
		List<Department> deplist = departmentService.findAll();
		for (Department t : deplist) {
			depMap.put(t.getId().toString(), t.getName());
		}
		departmentList = depMap;
	}

	public String save() {
		User user = this.getModel();
		if (user.getDepartment() == null
				|| user.getDepartment().getId() == null) {
			user.setDepartment(null);
		}
		if (user.getRole() == null || user.getRole().getId() == null) {
			user.setRole(null);
		}
		if (user.getTeam() == null || user.getTeam().getId() == null) {
			user.setTeam(null);
		}
		if (user.getSchool() == null || user.getSchool().getId() == null) {
			user.setSchool(null);
		}
		userService.saveOrUpdate(user);
		this.setResult(ConfirmMessage.User);
		fetchListData();
		return EDIT;
	}

	public String save2() {

		User user = this.getModel();
		if (user.getDepartment() == null
				|| user.getDepartment().getId() == null) {
			user.setDepartment(null);
		}
		if (user.getRole() == null || user.getRole().getId() == null) {
			user.setRole(null);
		}
		if (user.getTeam() == null || user.getTeam().getId() == null) {
			user.setTeam(null);
		}
		if (user.getSchool() == null || user.getSchool().getId() == null) {
			user.setSchool(null);
		}
		userService.saveOrUpdate(user);
		this.setResult(ConfirmMessage.User);
		this.setHomepage("/system/TodoEvent/list");
		fetchListData();
		return "other";
	}

	public String delete() {
		String ids = getRequest().getParameter("ids");
		String[] id = ids.split(",");
		for (String i : id) {
			userService.delete(userService.findById(Long.valueOf(i)));
		}

		return DELETE;
	}

	public String same() throws IOException {
		String same = getRequest().getParameter("same");

		User user = userService.getUserByLoginName(same);
		String result = "{sucess:true,same:false}";
		if (user == null) {

		} else {

			result = "{sucess:true,same:true}";
		}
		getResponse().getWriter().write(result);

		return NONE;
	}

	public String edit2() {
		fetchListData();
		return "other";
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public RoleService getRoleService() {
		return roleService;
	}

	public void setRoleService(RoleService roleService) {
		this.roleService = roleService;
	}

	public SchoolService getSchoolService() {
		return schoolService;
	}

	public void setSchoolService(SchoolService schoolService) {
		this.schoolService = schoolService;
	}

	public TeamService getTeamService() {
		return teamService;
	}

	public void setTeamService(TeamService teamService) {
		this.teamService = teamService;
	}

	public Map<String, String> getRoleList() {
		return roleList;
	}

	public void setRoleList(Map<String, String> roleList) {
		this.roleList = roleList;
	}

	public Map<String, String> getSchoolList() {
		return schoolList;
	}

	public void setSchoolList(Map<String, String> schoolList) {
		this.schoolList = schoolList;
	}

	public Map<String, String> getTeamList() {
		return teamList;
	}

	public void setTeamList(Map<String, String> teamList) {
		this.teamList = teamList;
	}

	// TODO 中文过滤
	public String autoCompleteAjax() {
		HttpServletResponse response = ServletActionContext.getResponse();
		HttpServletRequest request = ServletActionContext.getRequest();
		response.setHeader("Cache-Control", "no-cache");
		response.setContentType("text/plain;charset=GBK ");
		PrintWriter out = null;
		try {
			String q = request.getParameter("q");
			String limit = request.getParameter("limit");
			List<User> list = userService.findByAnything(q, Integer
					.valueOf(limit));
			// {id:id,name:name}
			String responseStr = "";
			// System.out.println(q);
			out = response.getWriter();
			for (User key : list) {
				responseStr = ("{id:") + (key.getId()) + (",name:\"")
						+ (key.getName()) + ("\"}");
				// System.out.println(responseStr);
				out.println(responseStr);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (Exception e) {

				}
			}
		}
		return null;
	}

	public String autoCompleteTMAjax() {
		autoCompleteRoleAjax("TM");
		return null;
	}

	public String autoCompleteCRAjax() {
		autoCompleteRoleAjax("CR");
		return null;
	}

	public String autoCompleteCCAjax() {
		autoCompleteRoleAjax("CC");
		return null;
	}

	public String autoCompleteRoleAjax(String role) {
		HttpServletResponse response = ServletActionContext.getResponse();
		HttpServletRequest request = ServletActionContext.getRequest();
		response.setHeader("Cache-Control", "no-cache");
		response.setContentType("text/plain;charset=GBK ");
		PrintWriter out = null;
		try {
			String q = request.getParameter("q");
			String limit = request.getParameter("limit");
			List<User> list = userService.findByAnythingWithRolename(role, q,
					Integer.valueOf(limit));
			// {id:id,name:name}
			String responseStr = "";
			// System.out.println(q);
			out = response.getWriter();
			for (User key : list) {
				responseStr = ("{id:") + (key.getId()) + (",name:\"")
						+ (key.getName()) + ("\"}");
				// System.out.println(responseStr);
				out.println(responseStr);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (Exception e) {

				}
			}
		}
		return null;
	}

	public Map<String, String> getDepartmentList() {
		return departmentList;
	}

	public void setDepartmentList(Map<String, String> departmentList) {
		this.departmentList = departmentList;
	}

	public DepartmentService getDepartmentService() {
		return departmentService;
	}

	public void setDepartmentService(DepartmentService departmentService) {
		this.departmentService = departmentService;
	}
}
